var upload = layui.upload;
var group_item = '<div class="group-item">' +
                    '<div class="group-parent">' +
                        '<div class="layui-inline">' +
                            '<input type="text" class="layui-input group_key" value="默认分组">' +
                        '</div>' +
                        '<div class="layui-inline">' +
                            '<a class="layui-btn layui-btn-normal group-add">添加规格</a>' +
                        '</div>' +
                        '<div class="layui-inline">'+
                            '<a class="layui-btn layui-btn-danger group-del">删除</a>' +
                        '</div>'+
                    '</div>' +
                    '<div class="group-son">' +
                        '<div class="layui-inline group-son-item">' +
                            '<div class="layui-inline">' +
                            '<input type="text" class="layui-input group_val" value="默认规格">' +
                            '</div>' +
                            '<div class="layui-inline">' +
                            '<a class="layui-btn layui-btn-danger group-item-del">删除</a>' +
                            '</div>' +
                        '</div>' +
                    '</div>'+
                 '</div>';

var group_son_item = '<div class="layui-inline group-son-item">' +
                        '<div class="layui-inline">' +
                            '<input type="text" class="layui-input group_val" value="默认规格">' +
                        '</div>' +
                        '<div class="layui-inline">' +
                            '<a class="layui-btn layui-btn-danger group-item-del">删除</a>' +
                        '</div>' +
                    '</div>';


function skuInit(tabObj){

    $('#group-add').click(function(){
        $('#group').append(group_item);
    });

    $('#group').on('click','.group-add',function(){
        $(this).parents('.group-parent').siblings('.group-son').append(group_son_item);
    });

    $('#group').on('click','.group-del',function(){
        let len = $('.group-item').length
        if(len<2){
            layer.msg('最少设置一组分组',{icon:2})
            return false;
        }
        $(this).parents('.group-item').remove();
         generateTable(tabObj);
    });


    $('#group').on('blur','.layui-input',function(){
        let val = $(this).val();
        if(!val){
            layer.msg('请输入内容',{icon:2})
            $(this).focus();
            return false;
        }
        generateTable(tabObj);
    });

    $('#group').on('click','.group-item-del',function(){
        let len = $(this).parents('.group-son').find('.group-son-item').length;
        if(len<2){
            layer.msg('最少设置一项规格',{icon:2})
            return false;
        }
        $(this).parents('.group-son-item').remove();
        generateTable(tabObj);
    });

    $('#group-table').on('blur','.layui-input',function(){
        let val = $(this).val();
        if(!val || val<0){
            $(this).val(0)
            layer.msg('不合法的数值,请重新输入!',{icon:2});
            return false;
        }

        getSkuData(tabObj);

    });

    $('#group-table').on('click','.batch',function(){
        let that = $(this);
        let name = that.attr('data-class');

        layer.prompt({title: '输入内容，并确认', formType: 0}, function(pass, index){
            $('.'+name).each(function(){
                $(this).val(pass);
            });
            getSkuData(tabObj);
            layer.close(index);
        });
    });

    let skus = $('#skus').val();


    skus ?  renderTable(tabObj) : generateTable(tabObj);
}

function cartesianProductOf() {
    return Array.prototype.reduce.call(arguments,function(a, b) {
        var ret = [];
        a.forEach(function(a) {
            b.forEach(function(b) {
                ret.push(a.concat([b]));
            });
        });
        return ret;
    }, [[]]);
}

// 获取sku属性
function getSkuAttr(){

    let attrs = [];
    $('.group-item').each(function(){
        let key = $(this).find('.group_key').val();
        let vals = [];
        $(this).find('.group_val').each(function(){
            vals.push($(this).val());
        });
        attrs.push({[key]:vals});
    });

    return attrs;
}


function renderTable(tabObj){

   let tbody = '';
   let attrs = JSON.parse($('#attrs').val());

   let spec = '';
   attrs.forEach((val)=>{
       let k = Object.keys(val)[0];
       let v = Object.values(val)[0];
       spec += '<div class="group-item">' +
                   '<div class="group-parent">' +
                       '<div class="layui-inline">' +
                            '<input type="text" class="layui-input group_key" value="'+k+'">' +
                       '</div>' +
                       '<div class="layui-inline">' +
                            '<a class="layui-btn layui-btn-normal group-add">添加规格</a>' +
                       '</div>' +
                       '<div class="layui-inline">'+
                            '<a class="layui-btn layui-btn-danger group-del">删除</a>' +
                       '</div>'+
                   '</div>' +
                   '<div class="group-son">';


       v.forEach((v1)=>{
           spec += '<div class="layui-inline group-son-item">' +
                       '<div class="layui-inline">' +
                       '<input type="text" class="layui-input group_val" value="'+v1+'">' +
                       '</div>' +
                       '<div class="layui-inline">' +
                       '<a class="layui-btn layui-btn-danger group-item-del">删除</a>' +
                       '</div>' +
                    '</div>';
       });
       spec += '</div>'+
           '</div>';
   });

   $('#group').html(spec);

   let skus = JSON.parse($('#skus').val());
   tbody += '<tr>';

   attrs.forEach((v)=>{
        tbody += '<th>';
        tbody += Object.keys(v)[0];
        tbody += '</th>';
   })

   tbody += '<th>图片</th>';

   tabObj.forEach((v) =>{
       if (v.type=='input'){
           tbody += '<th>' + v.val + '<a class="layui-btn layui-btn-xs batch" data-class="'+v.key+'">批量设置</a></th>';
       }else {
           tbody += '<th>' + v.val +'</th>';
       }
   })

   tbody += '</tr>';

   skus.forEach((val)=>{
        tbody += '<tr>';
        tbody += '<input type="hidden" class="id" value="'+val.id+'">';
        if (val.sku_id){
            tbody += '<input type="hidden" class="sku-id" value="'+val.sku_id+'">';
        }

        val.attr.forEach((v1) => {
            tbody += '<td class="attr">';
            tbody += v1;
            tbody += '</td>';
        });
        let img = val.image ? val.image : '/static/admin/img/upimg.png';
        tbody += '<td><img src="'+img+'" class="layui-upimg sku-img-up">' +
            '<input type="hidden" class="sku-image" value="'+img+'"></td>';

        tabObj.forEach((v2) =>{
            if (v2.type == 'input'){
                let input = val[v2.key] ? val[v2.key] : 0;
                tbody += '<td><input type="text" class="layui-input '+v2.key+'" value="'+input+'"></td>'
            } else  {
                tbody += '<td class="'+v2.key+'">'+val[v2.key]+'</td>';
            }

        })

        tbody += '</tr>';
   });

   $('#group-table').html(tbody);

    upload.render({
        elem: '.sku-img-up',
        accept: 'images',
        field: "image",
        url: "/store/upload",
        done: function(res){
            if(res.code==1){
            let that = this.item
                that.siblings('.sku-image').val(res.src);
                that.attr('src',res.src);
                getSkuData(tabObj)
            }
        }
    });

}


function generateTable(tabObj){
    let attrs = getSkuAttr();
    let keys = [],vals = [];

    if (attrs.length<1){
        return false;
    }

    $('#attrs').val(JSON.stringify(attrs));

    attrs.forEach((v)=> {
        keys.push(Object.keys(v)[0]);
        vals.push(Object.values(v)[0]);
    })

    let skus = [];
    let tbody = '';


    tbody += '<tr>';
    keys.forEach(function(item){
        tbody += '<th>';
        tbody += item;
        tbody += '</th>';
    });


    tbody += '<th>图片</th>';

    tabObj.forEach((v) =>{
        if (v.type=='input'){
            tbody += '<th>' + v.val + '<a class="layui-btn layui-btn-xs batch" data-class="'+v.key+'">批量设置</a></th>';
        }else {
            tbody += '<th>' + v.val +'</th>';
        }

    });


    tbody += '</tr>';

    skus = cartesianProductOf(...vals);

    skus.forEach((vals) => {
        tbody += '<tr>';
        vals.forEach((v) => {
            tbody += '<td class="attr">';
            tbody += v;
            tbody += '</td>';
        });
        tbody += '<td>' +
            '<img src="/static/admin/img/upimg.png"  class="layui-upimg sku-img-up">' +
            '<input type="hidden" class="sku-image"></td>';

        tabObj.forEach((v) =>{
            tbody += '<td><input type="text" class="layui-input '+v.key+'" value="0"></td>'
        })

        tbody += '</tr>';
    });

    $('#group-table').html(tbody);

    upload.render({
        elem: '.sku-img-up',
        accept: 'images',
        field: "image",
        url: "/store/upload",
        done: function(res){
            if(res.code==1){
            let that = this.item;
                that.siblings('.sku-image').val(res.src);
                that.attr('src',res.src);
                getSkuData(tabObj)
            }
        }
    });
}

function getSkuData(tabObj){
    let skuData = [];
    $('#group-table tr:not(:eq(0))').each(function(){
            let sku = {};
            let attr = [];
            $(this).find('.attr').each(function(){
                attr.push($(this).text());
            });

            let id = $(this).find('.id').val();

            if(id){
                sku.id = id;
            }

            let sku_id = $(this).find('.sku-id').val();

            if(sku_id){
                sku.sku_id = sku_id;
            }

            sku.attr = attr;
            let img = $(this).find('.sku-image').val();
            sku.image = img ? img : '';
            let that = $(this);
            tabObj.forEach((v)=>{
                let float = that.find('.'+v.key+'').val()
                let text = that.find('.'+v.key+'').text();
                if (v.type=='input'){
                    sku[v.key] = float;
                }else{
                    sku[v.key] = text;
                }
            })

            skuData.push(sku);
    });

    $('#skus').val(JSON.stringify(skuData));
}    